package initialize

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"gopkg.in/yaml.v2"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"week_one/user_srv/common/global"
	"week_one/user_srv/logic"
	user "week_one/user_srv/proto"
	"week_one/user_srv/vender/consul"
)

func init() {
	InitViper()
	InitNacos()
	InitZap()
}
func InitViper() {
	path := "./etc/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	global.NacosConfig = &global.NaCosConf{
		Host:        viper.GetString("NacosConf.Host"),
		Port:        viper.GetInt("NacosConf.Port"),
		DataId:      viper.GetString("NacosConf.DataId"),
		Group:       viper.GetString("NacosConf.Group"),
		NamespaceId: viper.GetString("NacosConf.NamespaceId"),
	}
	fmt.Println(global.NacosConfig, "//")
}
func InitNacos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   uint64(global.NacosConfig.Port),
		},
	}

	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	yaml.Unmarshal([]byte(content), &global.ServerConfig)
	fmt.Println(global.ServerConfig.UserConf, "==")
}
func InitZap() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		global.ServerConfig.ZapConf.LogUrl,
		global.ServerConfig.ZapConf.Stderr,
		global.ServerConfig.ZapConf.Stdout,
	}
	logger, _ := config.Build()
	zap.ReplaceGlobals(logger)
}
func InitGrpc() {
	GrpcServer := grpc.NewServer()
	Server := &logic.UserServer{}
	user.RegisterUserServer(GrpcServer, Server)
	grpc_health_v1.RegisterHealthServer(GrpcServer, health.NewServer())
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.ServerConfig.UserConf.Host, global.ServerConfig.UserConf.Port))
	if err != nil {
		panic(err)
	}
	consulClient := InitConsul()
	go func() {
		if err = GrpcServer.Serve(listen); err != nil && err != http.ErrAbortHandler {
			panic(err)
		}
	}()
	zap.S().Info("元神启动。。。。")
	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, syscall.SIGTERM, syscall.SIGINT)
	<-SigChan
	err = consulClient.Deregister(global.ServerConfig.ConsulConf.Id)
	if err != nil {
		panic(err)
	}
	GrpcServer.Stop()
}
func InitConsul() consul.RegistryClient {
	var (
		err      error
		BaseHost string
		BasePort int
	)
	global.ConsulClient, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	consulClient := consul.NewRegistryClient(global.ServerConfig.UserConf.Host, global.ServerConfig.UserConf.Port)
	ConsulMap, err := consulClient.FilterConsulById(global.ServerConfig.ConsulConf.Name)
	if err != nil {
		panic(err)
	}
	for _, v := range ConsulMap {
		BaseHost = v.Address
		BasePort = v.Port
	}
	if BaseHost != "" && BasePort != 0 {
		zap.S().Info("服务已注册")
		panic("服务已注册")
	}
	global.ServerConfig.ConsulConf.Id = uuid.NewString()
	err = consulClient.RegisterConsul(global.ServerConfig.ConsulConf.Id, global.ServerConfig.ConsulConf.Name, global.ServerConfig.ConsulConf.Tags)
	if err != nil {
		panic(err)
	}
	zap.S().Info("consul register success")
	return consulClient
}
